package com.videoweb.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.videoweb.model.UploadStatus;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UploadStatusMapper extends BaseMapper<UploadStatus> {
    
    /**
     * 根据文件哈希查找上传状态
     */
    @Select("SELECT * FROM upload_status WHERE file_hash = #{fileHash}")
    UploadStatus findByFileHash(@Param("fileHash") String fileHash);
    
    /**
     * 更新已上传分片信息
     */
    @Update("UPDATE upload_status SET uploaded_chunks = #{uploadedChunks}, updated_at = #{updatedAt} " +
            "WHERE file_hash = #{fileHash}")
    int updateUploadedChunks(@Param("fileHash") String fileHash, 
                            @Param("uploadedChunks") String uploadedChunks,
                            @Param("updatedAt") LocalDateTime updatedAt);
    
    /**
     * 更新上传状态
     */
    @Update("UPDATE upload_status SET status = #{status}, updated_at = #{updatedAt} " +
            "WHERE file_hash = #{fileHash}")
    int updateStatus(@Param("fileHash") String fileHash, 
                    @Param("status") String status,
                    @Param("updatedAt") LocalDateTime updatedAt);
    
    /**
     * 设置最终文件路径
     */
    @Update("UPDATE upload_status SET final_path = #{finalPath}, status = #{status}, updated_at = #{updatedAt} " +
            "WHERE file_hash = #{fileHash}")
    int updateFinalPath(@Param("fileHash") String fileHash, 
                       @Param("finalPath") String finalPath,
                       @Param("status") String status,
                       @Param("updatedAt") LocalDateTime updatedAt);
    
    /**
     * 查询指定用户的上传记录
     */
    @Select("SELECT * FROM upload_status WHERE user_id = #{userId} ORDER BY created_at DESC")
    List<UploadStatus> findByUserId(@Param("userId") Long userId);
    
    /**
     * 查询超时的上传记录（用于清理）
     */
    @Select("SELECT * FROM upload_status WHERE status IN ('uploading', 'merging') " +
            "AND created_at < #{timeoutTime}")
    List<UploadStatus> findTimeoutUploads(@Param("timeoutTime") LocalDateTime timeoutTime);
    
    /**
     * 删除超时的上传记录
     */
    @Update("DELETE FROM upload_status WHERE status IN ('uploading', 'merging') " +
            "AND created_at < #{timeoutTime}")
    int deleteTimeoutUploads(@Param("timeoutTime") LocalDateTime timeoutTime);
} 